<?php
/**
 * KePHP, Keep PHP easy!
 */

namespace CSService\Controller;


use CSService\Model\Command\Command;
use CSService\Model\Project\Project;
use CSService\Model\Server\Server;
use CSService\Model\User\User;
use Ke\Adm\DataList;
use Ke\Adm\Model;

class Curd extends Abs
{

	protected $models = [
		'user'    => [User::class, '用户'],
		'server'  => [Server::class, '服务器'],
		'project' => [Project::class, '项目'],
		'command' => [Command::class, '命令'],
	];

	/** @var DataList */
	public $data;

	public $model;

	public $modelName;

	/** @var Model */
	public $target;

	public $prefix = '';

	public $addAble = true;

	protected function onConstruct()
	{
		parent::onConstruct(); // TODO: Change the autogenerated stub
	}

	protected function getActionArgs(array $params): array
	{
		if (empty($params['data']['model']))
			throw new \Exception("Unset the model name!");
		$this->prefix = strtolower($params['data']['model']);
		if (!isset($this->models[$this->prefix]))
			throw new \Exception("Class {$this->prefix} does not exist!");
		list($this->model, $this->modelName) = $this->models[$this->prefix];
		return [$this->model];
	}

	public function index($model)
	{
		$this->data = $model::find();
	}

	public function edit($model)
	{
		$this->target = $model::findOne($this->web->tail(0));
	}

	public function post_edit($model)
	{
		if ($this->http->isPost($this->prefix) && $this->target->save($this->http->getSecurityData()) > 0) {
			$this->redirect($this->http->query('ref', "curd/{$this->prefix}"));
		}
	}
}